const express = require('express');
const router = express.Router();
const moment = require('moment');
const User = require('../models/User')
const Card = require('../models/Card');
const indexTabs = require('../config/config');
const Comment = require('../models/Comment')

//获取卡片信息
router.get('/getCardList', async (req, res) => {
    try {
        const randomCards = await Card.aggregate([{ $sample: { size: 10 } }]);
        if (randomCards.length > 0) {
            const cardList = [];
            for (const card of randomCards) {
                const author = await User.findById(card.author);
                const cardInfo = {
                    _id: card._id,
                    title: card.title,
                    content: card.content,
                    images: card.images,
                    like: card.likeCount,
                    tags: card.tags,
                    author: {
                        _id: author._id,
                        username: author.username,
                        avatar: author.avatar,
                    },
                };
                cardList.push(cardInfo);
            }
            res.status(200).json(cardList);
        } else {
            console.log('未找到随机卡片数据.');
            res.status(400).json({ error: "没有数据了" });
        }
    } catch (error) {
        console.log('获取卡片出错', error);
        res.status(500).json({ error: '获取随机卡片时出错' });
    }
})
//获取单一卡片的信息，用于展示卡片页面的
router.get('/getCardInfo', async (req, res) => {
    try {
        const id = req.query._id;
        const cardData = await Card.findOne({ _id: id });
        if (cardData) {
            const author = await User.findById(cardData.author);
            const commentIds = cardData.comment;
            const comments = await Comment.find({ _id: { $in: commentIds } })
            const commentData = await Promise.all(comments.map(async (comment) => {
                const commenter = await User.findById(comment.commenter);
                return {
                    commentId: comment._id,
                    author: {
                        _id: commenter._id,
                        username: commenter.username,
                        avatar: commenter.avatar,
                    },
                    content: comment.content,
                    createdAt: comment.createdAt,
                    like: comment.like,
                };
            }));
            const cardInfo = {
                cardData: cardData,
                author: {
                    _id: author._id,
                    uid: author.uid,
                    username: author.username,
                    avatar: author.avatar,
                },
                comments: commentData,
            }
            res.status(200).json(cardInfo)
        } else {
            console.log('没找到');
        }
    } catch (error) {
        console.log(error);
        res.status(500).json({
            message: "服务器错误"
        })
    }
    // console.log(id);
})

//上拉加载更多的接口
router.get('/addCardList', async (req, res) => {
    const { pageNum, pageSize, tags, pageCount } = req.query;
    const tabsid = parseInt(tags);
    let query = {};
    if (tabsid === 1) {
        const totalCount = await Card.countDocuments(); // 获取文档的总数
        const randomSkip = Math.floor(Math.random() * (totalCount - pageSize + 1)); // 生成随机的跳过值
        query = {}; // 空查询以获取随机数据
    } else {
        const selectedTab = indexTabs.indexTabs.find(tab => tab.tabsid === tabsid);
        if (selectedTab) {
            query.tags = selectedTab.name;
        } else {
            return res.status(400).json({ success: false, message: '参数错误' });
        }
    }
    //分页查询数据库,只要用户的用户名和头像，要卡片的标签，标题，喜欢的数量和图片
    const cardData = await Card.find(query).limit(parseInt(pageSize)).skip(parseInt(pageCount) * parseInt(pageSize)).populate({
        path: 'author',
        select: 'username avatar'
    }).select('tags title likeCount images');
    console.log(cardData);
    if (cardData.length === 0) {
        return res.status(404).json({ success: false, message: '查询失败' });
    }
    if (cardData.length < parseInt(pageSize)) {
        return res.status(200).json({ success: true, message: '查询成功', isOver: true, data: cardData });
    }
    res.status(200).json({ success: true, message: '查询成功', isOver: false, data: cardData });
});


//获取我喜欢的卡片的接口
router.get('/getlikeCard', async (req, res) => {
    try {
        const uid = req.query.uid;
        const user = await User.findOne({ uid }).populate('recentLikes');
        if (!user) {
            return res.status(404).json({ message: '用户不存在' });
        }
        const recentLikes = user.recentLikes;
        const cardList = [];
        for (const card of recentLikes) {
            const _author = await User.findById(card.author);
            const cardInfo = {
                _id: card._id,
                title: card.title,
                content: card.content,
                images: card.images,
                like: card.likeCount,
                tags: card.tags,
                author: {
                    _id: _author._id,
                    username: _author.username,
                    avatar: _author.avatar,
                },
            };
            cardList.push(cardInfo)
        }
        console.log(cardList);
        return res.status(200).json({ cardList });
    } catch (error) {
        return res.status(500).json({ message: '服务器错误' });
    }
})

//获取我收藏的卡片的接口
router.get('/getfavoritesCard', async (req, res) => {
    try {
        const uid = req.query.uid;
        const user = await User.findOne({ uid }).populate('favorites');
        if (!user) {
            return res.status(404).json({ message: '用户不存在' });
        }
        const favorites = user.favorites;
        console.log(favorites);
        const cardList = [];
        for (const card of favorites) {
            const _author = await User.findById(card.author);
            const cardInfo = {
                _id: card._id,
                title: card.title,
                content: card.content,
                images: card.images,
                like: card.likeCount,
                tags: card.tags,
                author: {
                    _id: _author._id,
                    username: _author.username,
                    avatar: _author.avatar,
                },
            };
            cardList.push(cardInfo)
        }
        console.log(cardList);
        return res.status(201).json({ cardList });
    } catch (error) {
        return res.status(500).json({ message: '服务器错误' });
    }
})

router.post('/addToWatchedHistory', async (req, res) => {
    try {
        const userId = req.body.params.userId;
        const cardId = req.body.params.cardId;
        // 检查用户和卡片是否存在
        const user = await User.findById(userId);
        const card = await Card.findById(cardId);
        if (!user || !card) {
            return res.status(404).json({ message: '用户或卡片未找到' });
        }
        // 将卡片的 ObjectId 添加到用户的观看卡片历史记录中
        user.watchedCardHistory.addToSet(card._id);
        // 保存用户文档
        await user.save();
        res.status(201).json({ message: '卡片已添加到观看历史记录' })
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: '发生错误' });
    }
})


router.get('/getWatchHistory', async (req, res) => {
    try {
        const uid = req.query.uid;
        const user = await User.findOne({ uid });
        if (!user) {
            return res.status(404).json({ error: '用户不存在' });
        }
        const watchedCardHistory = user.watchedCardHistory;
        const detailedHistory = await Card.find({ _id: { $in: watchedCardHistory } });
        const cardList = [];
        for (const card of detailedHistory) {
            const _author = await User.findById(card.author);
            const cardInfo = {
                _id: card._id,
                title: card.title,
                content: card.content,
                images: card.images,
                like: card.likeCount,
                tags: card.tags,
                author: {
                    _id: _author._id,
                    username: _author.username,
                    avatar: _author.avatar,
                },
            };
            cardList.push(cardInfo)
        }
        res.status(200).json(cardList);
    } catch (error) {
        console.error('获取用户观看历史记录失败', error);
        res.status(500).json({ error: '服务器错误' });
    }
})

router.post('/postCard', async (req, res) => {
    try {
        //获取当前系统时间
        const now = moment().format('YYYY-MM-DD HH:mm:ss');
        const { imgList, title, content, labels } = req.body.params;
        const authorId = req.body.params.userid;
        const author = await User.findById(authorId);
        const comments = [];
        if (!author) {
            return res.status(404).json({ message: '找不到作者' });
        }
        const tags = labels.map((tabsid) => {
            const tab = indexTabs.indexTabs.find((tab) => tab.tabsid === tabsid);
            return tab ? tab.name : '';
        });
        const newCard = new Card({
            title,
            content,
            images: imgList,
            author: authorId,
            tags,
            comments
        });
        await newCard.save();
        author.posts.push(newCard);
        await author.save();
        res.status(201).json({ message: '卡片创建成功', cardId: newCard._id });
    } catch (error) {
        res.status(500).json({ message: '内部服务器错误' });
    }
})
// 喜欢或取消喜欢卡片
router.post('/setLikeCard', async (req, res) => {
    try {
        const cardId = req.body.params.cardId;
        const currentUserUid = req.body.params.userId;
        // 查找当前用户
        const currentUser = await User.findOne({ _id: currentUserUid });
        // 查找要喜欢的卡片
        const card = await Card.findById(cardId);
        // console.log(card);
        // 检查卡片是否存在
        if (!card) {
            return res.status(404).json({ message: '卡片不存在', code: 404 });
        }
        // 检查用户是否已经喜欢了这个卡片
        const userLiked = currentUser.recentLikes.includes(cardId);
        if (userLiked) {
            // 用户已经喜欢了这张卡片，执行取消喜欢操作
            // 减少卡片的 like 字段减一
            card.like -= 1;
            // 从用户的喜欢列表中移除卡片的ID
            currentUser.recentLikes = currentUser.recentLikes.filter(likedCardId => likedCardId.toString() !== cardId);
            res.status(201).json({ message: '取消喜欢成功', code: 200 });
        } else {
            // 用户未喜欢这张卡片，执行喜欢操作
            // 增加卡片的 like 字段加一
            card.like += 1;
            // 更新用户的喜欢列表
            currentUser.recentLikes.push(cardId);
            res.status(200).json({ message: '喜欢成功', code: 200 });
        }
        // 保存卡片和用户数据
        await card.save();
        await currentUser.save();
    } catch (error) {
        console.error('操作卡片失败:', error);
        res.status(500).json({ message: '操作卡片失败' });
    }
});

router.post('/setCollectCard', async (req, res) => {
    try {
        const cardId = req.body.params.cardId;
        const currentUserUid = req.body.params.userId;
        const currentUser = await User.findOne({ _id: currentUserUid });
        const card = await Card.findById(cardId);
        if (!card) {
            return res.status(404).json({ message: '卡片不存在', code: 404 });
        }
        const userCollected = currentUser.favorites.includes(cardId);
        if (userCollected) {
            currentUser.favorites = currentUser.favorites.filter(collectedCardId => collectedCardId.toString() !== cardId);
            res.status(200).json({ message: '取消收藏成功', code: 200 });
        } else {
            currentUser.favorites.push(cardId);
            res.status(200).json({ message: '收藏成功', code: 200 });
        }
        await currentUser.save();
    } catch (error) {
        console.error('Operation failed:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});






// 删除卡片
router.delete('/deleteCard', async (req, res) => {
    try {
        const cardId = req.query.cardId;
        const currentUserUid = req.query.userId;
        // 查找要删除的卡片
        const card = await Card.findById(cardId);
        // 检查卡片是否存在
        if (!card) {
            return res.status(404).json({ message: '卡片不存在' });
        }
        // 检查当前用户是否是卡片的作者
        if (card.author.toString() !== currentUserUid) {
            return res.status(403).json({ message: '你无权删除这张卡片' });
        }
        // 找到卡片的作者
        const author = await User.findById(currentUserUid);
        // 从作者的帖子列表中移除卡片
        author.posts = author.posts.filter(postId => postId.toString() !== cardId);
        // 执行删除操作
        await Card.findByIdAndDelete(cardId);
        await author.save();
        res.status(200).json({ message: '卡片删除成功' });
    } catch (error) {
        console.error('删除卡片失败:', error);
        res.status(500).json({ message: '删除卡片失败' });
    }
});


router.get('/checkUserInteractions', async (req, res) => {
    try {
        const cardId = req.query.cardId;
        const userId = req.query.userId;
        // 查找用户
        const user = await User.findOne({ _id: userId });
        console.log(user);
        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }
        // 查找卡片
        const card = await Card.findById(cardId);
        if (!card) {
            return res.status(404).json({ message: 'Card not found' });
        }
        // 检查用户是否已经收藏该卡片
        const isCollected = user.favorites.includes(cardId);
        // 检查用户是否已经点赞该卡片
        const isLiked = user.recentLikes.includes(cardId);
        // 检查用户是否关注了卡片的作者
        const isFollowingAuthor = user.followingCount.includes(card.author.toString());
        const interactionStatus = {
            isCollected,
            isLiked,
            isFollowingAuthor,
        };
        res.status(200).json(interactionStatus);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});



module.exports = router